package com.sanmina.route.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sanmina.route.dao.RouteDao;
import com.sanmina.route.dao.RouteDaoImpl;
import com.sanmina.route.entity.Route;

import net.sf.json.JSONObject;

@WebServlet("/saveRoute")
public class RouteAction extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private boolean success = false;
	private String msg = "";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		try {
			RouteDao dao = new RouteDaoImpl();
			
			String name = req.getParameter("name");
			if(dao.isRouteExist(name).getRouteKey()==null){
				Route route = new Route();
				route.setName(name);
				this.success = dao.addRoute(route);
			}else{
				this.success = false;
				this.msg = "Duplicate Route Name !";
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		if (success) {
			msg = "Save Route Successfully!";
		} 
		JSONObject jo = new JSONObject();
		jo.put("msg", this.msg);
		jo.put("success", this.success);
		resp.setCharacterEncoding("UTF-8");
		resp.setHeader("Cache-Control", "no-cache");
		resp.setContentType("text/html;charset=UTF-8");
		resp.getWriter().print(jo);
		resp.getWriter().close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}

}
